package cn.tedu.practice2303.LSS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {
    private ServerSocket serverSocket2;
    public Server2(){
        try {
            System.out.println("正在启动服务器...");
            serverSocket2 = new ServerSocket(8888);
            System.out.println("服务器已启动!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while(true) {
                System.out.println("等待客户端连接...");
                Socket socket2 = serverSocket2.accept();
                System.out.println("有一个客户端连接了...");
                ClientHandler handler2 = new ClientHandler(socket2);
                Thread t = new Thread(handler2);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server2 server2 = new Server2();
        server2.start();
    }
}

class ClientHandler implements Runnable{
    private Socket socket2;
    private String host2;

    public ClientHandler(Socket socket2) {
        this.socket2 = socket2;
       host2 = socket2.getInetAddress().getHostAddress();
    }

    public void run(){
        try {
            InputStream is = socket2.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while((line=br.readLine())!=null){
                System.out.println(host2+"说:"+line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
